package com.tbit.common.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.tbit.common.constant.CommonConstant;
import org.slf4j.MDC;


import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 链路追踪工具类
 * @author Zhang Zhi Liang
 * @date 2024/4/23 11:54
 */
public class TraceUtil {
    public static final String REGEX = "-";

    /**
     * 网络请求。远程调用时获取traceId
     * 从header和参数中获取traceId
     * 从网关传入数据
     *
     * @param request 　HttpServletRequest
     * @return traceId
     */
    public static String getTraceIdByRequest(HttpServletRequest request) {
        String traceId = request.getParameter(CommonConstant.TRACE_ID);
        if (StrUtil.isBlank(traceId)) {
            traceId = request.getHeader(CommonConstant.TRACE_ID);
        }
        return traceId;
    }

    public static String getTraceIdByLocal() {
        return MDC.get(CommonConstant.TRACE_ID);
    }

    /**
     * 传递traceId至MDC
     *
     * @param traceId 　链路id
     */
    public static void setTraceId(String traceId) {
        if (StrUtil.isNotBlank(traceId)) {
            MDC.put(CommonConstant.TRACE_ID, traceId);
        }
    }

    /**
     * 构建traceId
     * @return
     */
    public static String buildTraceId() {
        // 获取当前时间
        LocalDateTime dateTime = LocalDateTime.now();
        // 生成8位日期字符串 ddHHMMSS
        String dateStr = String.format("%02d%02d%02d%02d-", dateTime.getDayOfMonth(), dateTime.getHour(), dateTime.getMinute(), dateTime.getSecond());
        return String.format("%s%s",dateStr,UUID.randomUUID().toString().replaceAll(REGEX, StrUtil.EMPTY));
    }

    /**
     * 清理traceId
     */
    public static void cleanTraceId() {
        MDC.clear();
    }

}
